<template>
	<view class="j-p-password">
		<view class="j-p-p-phone">验证手机号：{{ userInfo.phone }}</view>
		<view class="j-p-p-code-b">
			<u-input type="number" v-model="params.code" maxlength="6" :focus="true" placeholder="请输入验证码" />
			<u-button class="j-p-p-code-btn" type="success" size="mini" :disabled="isCodeDis" @click="postMobileCode">{{ codeBtnText }}</u-button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
export default {
	data() {
		return {
			userInfo: {},
			isCodeDis: false,
			codeBtnText: '获取验证码',
			params: {
				code: '',
				keyval: '',
				username: ''
			}
		};
	},
	onLoad() {
		// 获取当前登录用户的基本信息
		this.postGetUserInfo();
	},
	onNavigationBarButtonTap() {
		// 判断验证码是否为空
		if (this.$u.test.isEmpty(this.params.code)) {
			this.$refs.uToast.show({
				title: '验证码不能为空'
			});
			return false;
		}

		// 判断验证码唯一值是否为空
		if (this.$u.test.isEmpty(this.params.keyval)) {
			this.$refs.uToast.show({
				title: '请重新发送短信验证码'
			});
			return false;
		}
		// 赋值手机号参数
		this.params.username = this.userInfo.username;
		// 判断短信验证码是否正确
		this.postCheckMobileCode();
	},
	methods: {
		// 判断短信验证码是否正确
		postCheckMobileCode() {
			this.$u.api
				.postCheckMobileCode(this.params)
				.then(res => {
					console.log(res);
					uni.navigateTo({
						url: './pay-password-submit'
					});
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 获取短信验证码
		postMobileCode() {
			this.$u.api
				.postMobileCode({
					type: 2,
					mobile: this.userInfo.username
				})
				.then(res => {
					console.log(res);
					this.params.keyval = res.data.keyval;
					// 发送成功之后触发验证码倒计时
					this.timeInverted();
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 发送验证码倒计时
		timeInverted() {
			this.isCodeDis = true;
			let initial = 120;
			this.codeBtnText = `${initial}s`;
			let intercal = setInterval(() => {
				initial--;
				this.codeBtnText = `${initial}s`;
				if (initial == 0) {
					this.codeBtnText = '重新获取';
					this.isCodeDis = false;
					clearInterval(intercal);
				}
			}, 1000);

			this.$refs.uToast.show('发送成功');
		},
		// 获取当前登录用户的基本信息
		postGetUserInfo() {
			this.$u.api
				.postGetUserInfo()
				.then(res => {
					console.log(res);
					this.userInfo = res.data;
					let reg = /^(\d{3})\d{4}(\d{4})$/;
					this.userInfo.phone = res.data.username.replace(reg, '$1****$2');
				})
				.catch(err => {
					console.log(err);
				});
		}
	}
};
</script>

<style>
page {
	background-color: #f3f3f3;
}
</style>
<style scoped lang="scss">
.j-p-password {
	.j-p-p-phone {
		padding: 25rpx;
	}

	.j-p-p-code-b {
		display: flex;
		align-items: center;
		border-radius: 14rpx;
		padding: 16rpx 30rpx;
		background-color: #ffffff;

		.j-p-p-code-btn {
			width: 195rpx;
			height: 60rpx;
			font-size: 26rpx;
		}
	}
}
</style>
